<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数据结构之集合</title>
</head>
<body>
  <script type="text/javascript">
    function Set() {
      this.dataStore = [];
      this.add = add;
      this.remove = remove;
      this.has = has;
      this.size = size;
      this.show = show;
      this.union = union;
      this.intersect = intersect;
      this.difference = difference;
      this.subSet = subSet;
    }

    // 向集合中添加元素
    function add(data) {
      if (!this.has(data)) {
        this.dataStore.push(data);
      }
    }

    // 删除集合中的元素
    function remove(data) {
      var pos = this.dataStore.indexOf(data);
      if (pos !== -1) {
        this.dataStore.splice(pos, 1);
      }
    }

    // 判断集合中是否有某个元素
    function has(data) {
      return this.dataStore.indexOf(data) > -1;
    }

    // 求集合中元素个数
    function size() {
      return this.dataStore.length;
    }

    // 展示整个集合内容
    function show() {
      return this.dataStore;
    }

    // 求并集
    function union(set) {
      var tempSet = new Set();
      for (var i = 0; i < this.dataStore.length; i++) {
        tempSet.add(this.dataStore[i]);
      }
      for (var i = 0; i < set.dataStore.length; i++) {
        if (!tempSet.has(set.dataStore[i])) {
          tempSet.add(set.dataStore[i]);
        }
      }
      return tempSet;
    }

    // 求交集
    function intersect(set) {
      var tempSet = new Set();
      for (var i = 0; i < this.dataStore.length; i++) {
        if (set.has(this.dataStore[i])) {
          tempSet.add(this.dataStore[i]);
        }
      }
      return tempSet;
    }

    // 求差集
    function difference(set) {
      var tempSet = new Set();
      for (var i = 0; i < this.dataStore.length; i++) {
        if (!set.has(this.dataStore[i])) {
          tempSet.add(this.dataStore[i]);
        }
      }
      return tempSet;
    }

    // 判断一个集合是否是另一个集合的子集
    function subSet(set) {
      if (set.size() > this.size()) {
        return false;
      } else {
        for (var i = 0; i < set.dataStore.length; i++) {
          if (!this.has(set.dataStore[i])) {
            return false;
          }
        }
        return true;
      }
    }

    var set = new Set();
    set.add('first');
    set.add('second');
    set.add('third');
    // set.remove('first');
    var set1 = new Set();
    set1.add('first');
    set1.add('second');
    set1.add('fourth');
    console.log(set.show());
    console.log('并集：', set.union(set1).show());
    console.log('交集：', set.intersect(set1).show());
    console.log('差集：', set.difference(set1).show());
    var set2 = new Set();
    set1.add('first');
    set1.add('second');
    console.log('是否是子集：', set.subSet(set2));
  </script>
</body>
</html>